/*
 * ===========================================================================
 *       Filename:  rdcfg.c
 *        Created:  01/17/11 22:22:20
 *         Author:  LYF (Liu Yunfeng), liuyf.nju@gmail.com
 * ===========================================================================
 */

#include <stdio.h>
#include <string.h>

#define  CFGFILE "/root/sensor.cfg"

int get_arg(char *cmd, char *des)
{
	FILE *fp;
	char buffer[1024];
	size_t bytes_read;
	char *match, *match2;

	*des = '\0';

	fp = fopen( CFGFILE, "r");
	if( fp == NULL )
		return 0;
	bytes_read = fread(buffer, 1,sizeof(buffer), fp);
	fclose(fp);

	if( bytes_read == 0 || bytes_read == sizeof(buffer) )
		return 0;
	buffer[bytes_read] = '\0';

	match = buffer;
	while(1) {
		match = strstr( match, cmd );
		if( match == NULL ) return 0;
		if( ( ( match == buffer) ||
				isspace(*(match-1))) &&
		      ( isspace( *(match+strlen(cmd)) ) ||
				*(match+strlen(cmd)) == '=' ) )
			break;	//Perfect match
		match++;
	}
	match2 = strstr( match , "=");
	if( match2 == NULL ) return 0;

	bytes_read=sscanf( match2+1, "%s", des ); // Skip '='
	return bytes_read;
}

unsigned short str2num(char *src)
{
	unsigned short ret = 0;
	char *p = src;
	while(*p != '\0') {
		if( *p <'0' || *p > '9') return 0;
		ret = ret * 10 + *(p++) - '0';
	}
	return ret;
}

unsigned short get_node_id()
{
	char s_nodeid[10];
	if(get_arg("nodeid", s_nodeid) == 0) return 0;
	return str2num(s_nodeid);
}

unsigned short get_fs_type()
{
	char s_fstype[10];
	if(get_arg("fs_type", s_fstype) == 0) return 0;
	return str2num(s_fstype);
}

